﻿using App.Common;
using App.IService;
using App.Model;
using App.Model.DTO.User;
using App.Model.Enum;
using App.WebAPI.Utilty._MD5;
using App.WebAPI.Utilty.ApiResult;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace App.WebAPI.Controllers
{
    [Route("[controller]/[Action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IUserInfoService _iUserInfoService;
        private IRoleService _iRoleService;
        public LoginController(IUserInfoService iUserInfoService, IRoleService iRoleService)
        {
            _iUserInfoService = iUserInfoService;
            _iRoleService = iRoleService;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        //[HttpGet]
        //public IActionResult GetValidateCodeImages(string t)
        //{
        //    var validateCodeString = Tools.CreateValidateString();
        //    //将验证码记入缓存中
        //    MemoryHelper.SetMemory(t, validateCodeString, 5);
        //    //接收图片返回的二进制流
        //    byte[] buffer = Tools.CreateValidateCodeBuffer(validateCodeString);
        //    return File(buffer, @"image/jpeg");
        //}
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> CheckLogin(LoginRequestInput req)
        {
            //var currCode = MemoryHelper.GetMemory(req.ValidateKey);
            string pwd = MD5Helper.MD5Encrypt32(req.Password);
            //数据校验
            if (string.IsNullOrEmpty(req.UserName) || string.IsNullOrEmpty(req.Password))
            {
                return ApiResultHelper.Error("参数不能为空");
            }
            var user = await _iUserInfoService.FindAsync(c => c.UserName == req.UserName && c.UserPassword == pwd);
            if (user != null)
            {
                //登录成功
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name,user.Id),
                    new Claim(ClaimTypes.Name,user.NickName),
                    new Claim(ClaimTypes.Name,user.Email),
                    new Claim(ClaimTypes.Name,user.UserName),
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:5167",
                    audience: "http://localhost:5167",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddDays(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken, true);
            }
            else
            {
                return ApiResultHelper.Error("账号或密码错误");
            }

        }
        /// <summary>
        /// 账号密码注册
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Register(RegisterRequestInput req)
        {
            //var currCode = MemoryHelper.GetMemory(req.ValidateKey);
            //数据校验
            if (string.IsNullOrEmpty(req.UserName) || string.IsNullOrEmpty(req.Password))
            {
                return ApiResultHelper.Error("参数不能为空");
            }
            var id = GuidCombGenerator.GenerateCombGuid32();
            var roleType = EnumUserRoleType.ORDINARY_USER;
            var isEnable = EnumUserIsEnableType.ENABLE;
            UserInfo user = new UserInfo
            {
                Id = id,
                UserName = req.UserName,
                NickName = req.NickName,
                //加密密码
                UserPassword = MD5Helper.MD5Encrypt32(req.Password),
                Email = req.Email,
                CreateAt = DateTime.Now,
                RoleType = roleType,
                RoleId = "B17F008434D7A1EF4C097D6964D0F612",
                IsEnable = isEnable,
                UpdateAt = DateTime.Now

            };
            var oldUserName = await _iUserInfoService.FindAsync(c => c.UserName == req.UserName);
            var oldNickName = await _iUserInfoService.FindAsync(c => c.NickName == req.NickName);
            var oldEmail = await _iUserInfoService.FindAsync(c => c.Email == req.Email);
            if (oldUserName != null) return ApiResultHelper.Error("账号已存在");
            if (oldNickName != null) return ApiResultHelper.Error("昵称已存在");
            if (oldEmail != null) return ApiResultHelper.Error("邮箱已存在");
            bool b = await _iUserInfoService.CreateAsync(user);
            if (!b) return ApiResultHelper.Error("添加失败，服务器异常");
            return ApiResultHelper.Success(user, true);
        }
        /// <summary>
        /// 邮箱注册
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> EmailRegister(EmailRegisterRequestInput req)
        {
            //var currCode = MemoryHelper.GetMemory(req.ValidateKey);
            //数据校验
            if (string.IsNullOrEmpty(req.UserName) || string.IsNullOrEmpty(req.Password) || string.IsNullOrEmpty(req.ConfirmPassword) || string.IsNullOrEmpty(req.Email) || string.IsNullOrEmpty(req.ValidateCode))
            {
                return ApiResultHelper.Error("参数不能为空");
            }
            if (req.Password != req.ConfirmPassword)
            {
                return ApiResultHelper.Error("两次密码输入不一样！");
            }
            var validateCodeKey = req.ValidateCode + "register";
            var currCode = MemoryHelper.GetMemory(validateCodeKey)?.ToString();
            if (currCode == null)
            {
                return ApiResultHelper.Error("验证码已失效，请重新获取");
            }
            if (req.ValidateCode != currCode)
            {
                return ApiResultHelper.Error("验证码错误！");
            }

            MemoryHelper.RemoveMemory(validateCodeKey);
            var id = GuidCombGenerator.GenerateCombGuid32();
            var roleType = EnumUserRoleType.ORDINARY_USER;
            var isEnable = EnumUserIsEnableType.ENABLE;
            UserInfo user = new UserInfo
            {
                Id = id,
                UserName = req.UserName,
                NickName = req.UserName,
                UserPassword = MD5Helper.MD5Encrypt32(req.ConfirmPassword),
                Email = req.Email,
                CreateAt = DateTime.Now,
                RoleType = roleType,
                RoleId = "B17F008434D7A1EF4C097D6964D0F612",
                IsEnable = isEnable,
                UpdateAt = DateTime.Now

            };
            var oldUserName = await _iUserInfoService.FindAsync(c => c.UserName == req.UserName);
            var oldEmail = await _iUserInfoService.FindAsync(c => c.Email == req.Email);
            if (oldUserName != null) return ApiResultHelper.Error("账号已存在");
            if (oldEmail != null) return ApiResultHelper.Error("邮箱已存在");
            bool b = await _iUserInfoService.CreateAsync(user);
            if (!b) return ApiResultHelper.Error("注册失败，服务器异常");
            return ApiResultHelper.Success(user, true);
        }

        /// <summary>
        /// 邮箱验证码登录
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> EmailLogin(EmailLoginRequestInput req)
        {
            // 数据校验
            if (string.IsNullOrWhiteSpace(req.Email) || string.IsNullOrWhiteSpace(req.ValidateCode))
            {
                return ApiResultHelper.Error("邮箱或验证码不能为空");
            }

            var user = await _iUserInfoService.FindAsync(c => c.Email == req.Email);
            if (user == null)
            {
                return ApiResultHelper.Error("邮箱不存在");
            }

            try
            {
                var currCode = MemoryHelper.GetMemory(req.ValidateCode)?.ToString();
                if (currCode == null)
                {
                    return ApiResultHelper.Error("验证码已失效，请重新获取");
                }

                // 比较验证码
                if (req.ValidateCode != currCode)
                {
                    return ApiResultHelper.Error("验证码错误！");
                }
                MemoryHelper.RemoveMemory(req.ValidateCode);
                // 验证码正确，登录成功
                var claims = new Claim[]
                {
            new Claim(ClaimTypes.Name, user.Id),
            new Claim(ClaimTypes.Name, user.NickName),
            new Claim(ClaimTypes.Name, user.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:5167",
                    audience: "http://localhost:5167",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddDays(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken, true);
            }
            catch (ArgumentException ex)
            {
                return ApiResultHelper.Error($"验证码已失效，请重新获取: {ex.Message}");
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"登录失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ResetPassword(ResetPasswordRequestInput req)
        {
            var user = await _iUserInfoService.FindAsync(c => c.Email == req.Email);
            
            if (user == null)
            {
                return ApiResultHelper.Error("邮箱不存在");
            }
            try
            {
                var validateCodeKey = req.ValidateCode + "resetPwd";
                var currCode = MemoryHelper.GetMemory(validateCodeKey)?.ToString();
                if (currCode == null)
                {
                    return ApiResultHelper.Error("验证码已失效，请重新获取");
                }

                // 比较验证码
                if (req.ValidateCode != currCode)
                {
                    return ApiResultHelper.Error("验证码错误！");
                }
                MemoryHelper.RemoveMemory(validateCodeKey);
                var newPwd = MD5Helper.MD5Encrypt32(req.ConfirmPassword);
                user.UserPassword = newPwd;
                bool b = await _iUserInfoService.EditAsync(user);
                if (!b) return ApiResultHelper.Error("重置密码失败，服务器异常");
                return ApiResultHelper.Success("重置密码成功", b);

            }
            catch (ArgumentException ex)
            {
                return ApiResultHelper.Error($"验证码已失效，请重新获取: {ex.Message}");
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"重置密码失败: {ex.Message}");
            }
        }
    }
}
